import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { computed, ref } from 'vue'
import { getRecentChatsMenu, updateSidebarWithRecentChats } from '@/utils/chatUtils'
import { ErrorHandler } from '@/utils/errorHandler'

// 定义侧边栏项接口
interface SidebarItem {
  key: string
  label: string
  icon: string
  path?: string
  parent?: string
  children?: SidebarItem[]
}

// 扩展路由元信息接口
declare module 'vue-router' {
  interface RouteMeta {
    title?: string
    requiresAuth?: boolean
    sidebar?: SidebarItem
    permissions?: string[]
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/chat-detail',
    name: 'ChatDetail',
    component: () => import('../views/chat/ChatDetail.vue'),
    meta: {
      title: '智库问答详情',
      requiresAuth: true
    }
  },
  {
    path: '/doc-assistant',
    name: 'DocAssistantFull',
    component: () => import('../views/assistant/DocAssistant.vue'),
    meta: {
      title: '文档助手',
      requiresAuth: true
    }
  },
  {
    path: '/',
    component: () => import('../views/layout/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/dashboard/Dashboard.vue'),
        meta: {
          title: '首页',
          requiresAuth: true,
          sidebar: {
            key: 'dashboard',
            label: '首页',
            path: '/',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z" fill="currentColor"/></svg>`
          }
        }
      },
      {
        path: 'user-permission',
        name: 'UserPermission',
        component: () => import('../views/admin/UserPermission.vue'),
        meta: {
          title: '角色管理',
            showPageHeader: true,
          requiresAuth: true,
          sidebar: {
            key: 'user-permission',
            label: '角色管理',
            path: '/user-permission',
            icon: `<svg viewBox="0 0 24 24" width="24" height="24"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
          }
        }
      },
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('../views/chat/Chat.vue'),
        meta: {
          title: '智库问答',
          showPageHeader: true,
          requiresAuth: true,
          sidebar: {
            key: 'chat',
            label: '智库问答',
            path: '/chat',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4l4 4 4-4h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" fill="currentColor"/></svg>`
          }
        }
      },
      {
        path: 'chat/:chatId',
        name: 'ChatWithId',
        component: () => import('../views/chat/Chat.vue'),
        meta: {
          title: '智库问答',
          showPageHeader: true,
          requiresAuth: true,
          permissions: ['admin', 'user'],
          sidebar: {
            key: 'chat',
            label: '智库问答',
            path: '/chat',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4l4 4 4-4h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" fill="currentColor"/></svg>`
          }
        }
      },
      {
        path: 'knowledge-plus',
        name: 'KnowledgePlus',
        component: () => import('../views/knowledge/KnowledgePlus.vue'),
        meta: {
          title: '智库+',
          showPageHeader: true,
          sidebar: {
            key: 'knowledge-plus',
            label: '智库+',
            path: '/knowledge-plus',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="currentColor"/></svg>`
          }
        }
      },
      {
        path: 'knowledge-plus/chart-query',
        name: 'ChartQuery',
        component: () => import('../views/chat/ChartQuery.vue'),
        meta: {
          title: '图表查询',
          showPageHeader: true,
          requiresAuth: true,
          sidebar: {
            key: 'chart-query',
            label: '图表查询',
            path: '/knowledge-plus/chart-query',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="1em" height="1em" viewBox="0 0 14 14"><g><path d="M6.5625,5.48286C5.8413,5.42609,5.15922,5.23022,4.54306,4.92206C4.4557,5.44498,4.40089,5.9957,4.3822,6.5625L6.5625,6.5625L6.5625,5.48286ZM7.4375,5.48286L7.4375,6.5625L9.61781,6.5625C9.59911,5.9957,9.5443,5.445,9.45694,4.92206C8.8408,5.23022,8.1587,5.42609,7.4375,5.48286ZM6.5625,8.51714L6.5625,7.4375L4.38219,7.4375C4.40089,8.0043,4.4557,8.555,4.54306,9.07794C5.1592,8.76978,5.8413,8.57391,6.5625,8.51714ZM7.4375,8.51714C8.1587,8.57391,8.84078,8.76978,9.45694,9.07794C9.5443,8.55502,9.59911,8.0043,9.6178,7.4375L7.4375,7.4375L7.4375,8.51714ZM6.5625,13.9866C3.045,13.7696,0.230359,10.955,0.0134375,7.4375L0,7.4375L0,6.5625L0.0134375,6.5625C0.230375,3.045,3.045,0.230359,6.5625,0.0134375L6.5625,0L7.4375,0L7.4375,0.0134375C10.955,0.230375,13.7696,3.045,13.9866,6.5625L14,6.5625L14,7.4375L13.9866,7.4375C13.7696,10.955,10.955,13.7696,7.4375,13.9866L7.4375,14L6.5625,14L6.5625,13.9866ZM7.4375,9.39556L7.4375,12.859C7.53912,12.8515,7.64054,12.8414,7.74164,12.8287C8.07033,12.5712,8.39813,12.1467,8.69225,11.5585C8.92495,11.093,9.11958,10.5565,9.2698,9.9693C8.70604,9.65162,8.08175,9.45613,7.4375,9.39556ZM6.5625,9.39556C5.91825,9.45614,5.29396,9.65161,4.7302,9.96927C4.88042,10.5564,5.07505,11.093,5.30775,11.5585C5.60188,12.1467,5.92967,12.5712,6.25838,12.8287C6.35897,12.8413,6.46038,12.8515,6.5625,12.859L6.5625,9.39556ZM7.4375,1.14106L7.4375,4.60448C8.08176,4.54392,8.70605,4.34845,9.26981,4.03078C9.11958,3.44361,8.92497,2.90702,8.69225,2.44158C8.39813,1.85334,8.07033,1.42887,7.74162,1.17138C7.64053,1.15865,7.53912,1.14854,7.4375,1.14106ZM6.5625,1.14106C6.46088,1.14854,6.35946,1.15865,6.25836,1.17138C5.92967,1.42888,5.60188,1.85334,5.30775,2.44158C5.07502,2.90705,4.88041,3.44367,4.73017,4.03088C5.29393,4.34854,5.91824,4.54398,6.5625,4.60447L6.5625,1.14106ZM10.4933,6.5625L12.859,6.5625C12.7647,5.28258,12.2605,4.11664,11.477,3.19555C11.138,3.66949,10.7263,4.0869,10.257,4.43234C10.3884,5.09848,10.4702,5.81459,10.4933,6.5625ZM10.4933,7.4375C10.4702,8.18541,10.3884,8.90152,10.257,9.56766C10.7263,9.9131,11.138,10.3305,11.477,10.8045C12.2605,9.88336,12.7647,8.71742,12.859,7.4375L10.4933,7.4375ZM1.14105,6.5625L3.50672,6.5625C3.52978,5.81459,3.61156,5.09848,3.74297,4.43234C3.27373,4.0869,2.86201,3.66949,2.52305,3.19555C1.73955,4.11664,1.23527,5.28258,1.14105,6.5625ZM1.14105,7.4375C1.23527,8.71742,1.73955,9.88336,2.52305,10.8045C2.862,10.3305,3.27372,9.9131,3.74295,9.56766C3.61156,8.90152,3.52978,8.18541,3.50672,7.4375L1.14105,7.4375ZM10.0303,10.5051C9.81383,11.252,9.5303,11.9116,9.19617,12.4508C9.80498,12.2052,10.3632,11.8607,10.8509,11.437C10.6204,11.0909,10.3444,10.7775,10.0303,10.5051ZM3.9697,10.5051C3.6556,10.7775,3.37959,11.091,3.14911,11.437C3.63681,11.8607,4.19505,12.2052,4.80383,12.4508C4.4697,11.9116,4.18617,11.252,3.9697,10.5051ZM9.19617,1.54923C9.5303,2.08841,9.81383,2.74795,10.0303,3.49494C10.3444,3.22249,10.6204,2.90902,10.8509,2.56295C10.3632,2.13931,9.80495,1.79477,9.19617,1.54923ZM4.80383,1.54923C4.19508,1.79475,3.63689,2.13927,3.14922,2.56286C3.37973,2.90889,3.6557,3.22237,3.96972,3.49489C4.18619,2.74794,4.46972,2.08841,4.80383,1.54923Z" fill="currentColor" fill-opacity="1"/></g></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'knowledge-plus/doc-assistant',
        name: 'DocAssistant',
        redirect: '/doc-assistant'
      },
      {
        path: 'knowledge-plus/solution-assistant',
        name: 'SolutionAssistant',
        component: () => import('../views/assistant/SolutionAssistant.vue'),
        meta: {
          title: '标书助手',
          sidebar: {
            key: 'solution-assistant',
            label: '标书助手',
            path: '/knowledge-plus/solution-assistant',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'knowledge-plus/review-assistant',
        name: 'ReviewAssistant',
        component: () => import('../views/assistant/ReviewAssistant.vue'),
        meta: {
          title: '审核助手',
          sidebar: {
            key: 'review-assistant',
            label: '审核助手',
            path: '/knowledge-plus/review-assistant',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'knowledge-plus/translation-assistant',
        name: 'TranslationAssistant',
        component: () => import('../views/assistant/TranslationAssistant.vue'),
        meta: {
          title: '翻译助手',
          sidebar: {
            key: 'translation-assistant',
            label: '翻译助手',
            path: '/knowledge-plus/translation-assistant',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M5 8l6 6M4 14l6-6M15 5l6 6M14 11l6-6" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'knowledge-plus/ocr-recognition',
        name: 'OcrRecognition',
        component: () => import('../views/tools/OcrRecognition.vue'),
        meta: {
          title: '图文识别',
          sidebar: {
            key: 'ocr-recognition',
            label: '图文识别',
            path: '/knowledge-plus/ocr-recognition',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'knowledge-graph',
        name: 'KnowledgeGraph',
        component: () => import('../views/knowledge/KnowledgeGraph.vue'),
        meta: {
          title: '知识图谱',
          sidebar: {
            key: 'knowledge-graph',
            label: '知识图谱',
            path: '/knowledge-graph',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><circle cx="12" cy="12" r="3" fill="currentColor"/><circle cx="6" cy="6" r="2" fill="currentColor"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'personal-knowledge',
        name: 'PersonalKnowledge',
        component: () => import('../views/knowledge/PersonalKnowledge.vue'),
        meta: {
          title: '个人知识库',
          sidebar: {
            key: 'personal-knowledge',
            label: '个人知识库',
            path: '/personal-knowledge',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/></svg>`
          }
        }
      },
      // 近期对话父菜单（无页面）
      {
        path: 'recent-chats-parent',
        name: 'RecentChatsParent',
        component: () => import('../views/chat/Chat.vue'), // 默认跳转到智能问答
        meta: {
          title: '近期对话',
          sidebar: {
            key: 'recent-chats-parent',
            label: '近期对话',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>`
          }
        }
      },
      // 管道施工
      {
        path: 'pipeline-construction',
        name: 'PipelineConstruction',
        component: () => import('../views/chat/Chat.vue'),
        meta: {
          title: '管道施工',
          sidebar: {
            key: 'pipeline-construction',
            label: '管道施工',
            parent: 'recent-chats-parent',
            path: '/chat?topic=pipeline-construction',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M3 12h18m-9-9v18" stroke="currentColor" stroke-width="2" fill="none"/></svg>`
          }
        }
      },
      // 管道维修
      {
        path: 'pipeline-maintenance',
        name: 'PipelineMaintenance',
        component: () => import('../views/chat/Chat.vue'),
        meta: {
          title: '管道维修',
          sidebar: {
            key: 'pipeline-maintenance',
            label: '管道维修',
            parent: 'recent-chats-parent',
            path: '/chat?topic=pipeline-maintenance',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`
          }
        }
      },
      // 焊接施工注意
      {
        path: 'welding-construction',
        name: 'WeldingConstruction',
        component: () => import('../views/chat/Chat.vue'),
        meta: {
          title: '焊接施工注意',
          sidebar: {
            key: 'welding-construction',
            label: '焊接施工注意',
            parent: 'recent-chats-parent',
            path: '/chat?topic=welding-construction',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`
          }
        }
      },
      // 查看更多
      {
        path: 'recent-chats',
        name: 'RecentChats',
        component: () => import('../views/chat/RecentChats.vue'),
        meta: {
          title: '查看更多',
          sidebar: {
            key: 'recent-chats',
            label: '查看更多',
            parent: 'recent-chats-parent',
            path: '/recent-chats',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" fill="none"/></svg>`
          }
        }
      },
      {
        path: 'knowledge-plus/result-matching',
        name: 'ResultMatching',
        component: () => import('../views/ResultMatching/index.vue'),
        meta: {
          title: '成果匹配',
          sidebar: {
            key: 'result-matching',
            label: '成果匹配',
            path: '/knowledge-plus/result-matching',
            icon: `<svg viewBox="0 0 24 24" width="1em" height="1em"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>`,
            parent: 'knowledge-plus'
          }
        }
      },
      {
        path: 'enterprise-category',
        name: 'EnterpriseCategory',
        component: () => import('../views/admin/EnterpriseCategory/index.vue'),
        meta: {
          title: '企业库分类',
        }
      },
      {
        path: 'enterprise-knowledge',
        name: 'EnterpriseKnowledge',
        component: () => import('../views/admin/EnterpriseKnowledge/index.vue'),
        meta: {
          title: '企业知识库',
        }
      },
      {
        path: 'review-standards',
        name: 'ReviewStandards',
        component: () => import('../views/admin/ReviewStandards.vue'),
        meta: {
          title: '评审标准文件',
        }
      },
      {
        path: 'content-config',
        name: 'ContentConfig',
        component: () => import('../views/admin/ContentConfig.vue'),
        meta: {
          title: '文案配置',
        }
      },
      {
        path: 'user-management',
        name: 'UserManagement',
        component: () => import('../views/admin/UserManagement/index.vue'),
        meta: {
          title: '用户管理',
        }
      },
      {
        path: 'department-management',
        name: 'DepartmentManagement',
        component: () => import('../views/admin/DepartmentManagement/index.vue'),
        meta: {
          title: '部门管理',
        }
      },
      {
        path: 'role-management',
        name: 'RoleManagement',
        component: () => import('../views/admin/RoleManagement/index.vue'),
        meta: {
          title: '角色管理',
        }
      },
      {
        path: 'menu-mange',
        name: 'MenuManagement',
        component: () => import('../views/admin/MenuManagement/index.vue'),
        meta: {
          title: '菜单管理',
        }
      },
      {
        path: 'conflict-detection',
        name: 'ConflictDetection',
        component: () => import('../views/admin/ConflictDetection/index.vue'),
        meta: {
          title: '冲突检测',
        }
      },
      {
        path: 'conflict-detection/:id',
        name: 'ConflictDetectionDetail',
        component: () => import('../views/admin/ConflictDetection/Detail.vue'),
        meta: {
          title: '冲突检测详情',
        }
      },

    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

// 获取用户角色
function getUserRole(): string {
  return localStorage.getItem('userRole') || 'user'
}

// 检查权限
function hasPermission(permissions?: string[]): boolean {
  if (!permissions || permissions.length === 0) return true
  const userRole = getUserRole()
  return permissions.includes(userRole)
}

// 动态生成侧边栏项（根据当前用户权限过滤）
export async function getSidebarItems(): Promise<any[]> {
  const children = routes.find(route => route.path === '/')?.children || []
  const items = children.filter(child => {
    const sidebar = child.meta?.sidebar
    const permissions = child.meta?.permissions
    return sidebar && hasPermission(permissions)
  })

  // 构建层级结构
  const result: any[] = []
  const parentMap = new Map()

  items.forEach(item => {
    const sidebar = item.meta!.sidebar!
    if (sidebar.parent) {
      // 子项
      if (!parentMap.has(sidebar.parent)) {
        parentMap.set(sidebar.parent, [])
      }
      parentMap.get(sidebar.parent).push(sidebar)
    } else {
      // 父项
      result.push(sidebar)
    }
  })

  // 为父项添加子项
  result.forEach(item => {
    if (parentMap.has(item.key)) {
      item.children = parentMap.get(item.key)
    }
  })

  // 动态更新近期对话菜单
  try {
    const recentChatsMenu = await getRecentChatsMenu(3)
    return updateSidebarWithRecentChats(result, recentChatsMenu)
  } catch (error) {
    console.error('更新近期对话菜单失败:', error)
    return result
  }
}

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') !== null
  console.log(to.meta)
  console.log('路由守卫检查:', { path: to.path, name: to.name, isAuthenticated })

  // 如果要去登录页，清除所有错误处理标记并直接放行
  if (to.name === 'Login') {
    // 清除401错误处理标记
    sessionStorage.removeItem('handling_401_error')
    sessionStorage.removeItem('redirecting_to_login')
    // 确保登录页能正确渲染
    next()
    return
  }

  // 如果未登录且需要认证，跳转到登录页
  if (to.meta.requiresAuth && !isAuthenticated) {
    console.log('需要认证但未登录，跳转到登录页')
    next({ name: 'Login' })
    return
  }

  // 如果已登录，检查权限
  if (isAuthenticated && to.meta.permissions && !hasPermission(to.meta.permissions)) {
    console.log('权限不足，跳转到有权限的页面')
    const userRole = getUserRole()
    // 根据用户角色跳转到合适的页面
    if (userRole === 'user') {
      next({ name: 'Chat' })
    } else {
      next({ name: 'Dashboard' })
    }
    return
  }

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 十一智库系统`
  } else {
    document.title = '十一智库系统'
  }

  next()
})

// 全局后置守卫 - 处理401错误
router.afterEach((to, from) => {
  // 检查是否有401错误标记
  if (sessionStorage.getItem('handling_401_error') === 'true') {
    console.log('路由后置守卫：检测到401错误处理标记')
    // 清除标记
    sessionStorage.removeItem('handling_401_error')
  }
})

// 全局错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  
  // 检查是否是401相关错误
  if (error.message?.includes('401') || error.message?.includes('未授权')) {
    ErrorHandler.handle401Error()
  } else {
    // 其他路由错误处理
    console.error('路由错误:', error)
  }
})

export default router

// 响应式的侧边栏项
const sidebarItemsRef = ref<any[]>([])

// 初始化侧边栏项
getSidebarItems().then(items => {
  sidebarItemsRef.value = items
})

// 导出响应式的侧边栏项
export const sidebarItems = computed(() => sidebarItemsRef.value)

// 刷新侧边栏项的函数
export async function refreshSidebarItems() {
  const items = await getSidebarItems()
  sidebarItemsRef.value = items
}

